package study.springcloud.gateway.filter.global;

import cn.hutool.core.date.StopWatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import study.springcloud.gateway.support.utils.MdcUtils;
import study.springcloud.gateway.support.utils.WebUtils;

@Slf4j
//@Component
public class CustomGlobalFilter implements GlobalFilter, org.springframework.core.Ordered {

    @Override
    public int getOrder() {
        return 2;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        StopWatch stopWatch = StopWatch.create("");
        //
        String requestId = WebUtils.getRequestId(exchange);
        MdcUtils.put(requestId);
        log.info(">>>>>>>>>> custom GlobalFilter, order= {}", 1);
        //
        Mono<Void> mono;
        try {
            mono = chain.filter(exchange);
        } finally {
            log.info("cost time [{}] ms", stopWatch.getTotalTimeMillis());
            MdcUtils.remove();
        }
        //构建新的 exchange 并放回到过滤链
        return mono;
    }
}
